﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using FDStudio.Core.Common.Constants;
using FDStudio.Core.Entities;
using FDStudio.Core.Entities.Factories;
using FDStudio.Core.Entities.Query;
using FDStudio.Core.Repositories;
using FDStudio.Core.Runtime;

namespace FDStudio.Core.Services
{
    /*
     CreatedOn: 2018-01-30
     CreatedBy: Jackie Lee(天宇遊龍)
     */
    /// <summary>
    /// 服务基类
    /// </summary>
    public class ServiceBase<T> : IService<T> where T : class, IEntity
    {
        //private IRepositoryBase<T> _repository;

        //public ServiceBase(IRepositoryBase<T> repository)
        //{
        //    _repository = repository;
        //}

        ///// <summary>
        ///// 获取当仓储
        ///// </summary>
        ///// <typeparam name="U"></typeparam>
        ///// <returns></returns>
        //protected U Repository<U>()
        //{
        //    return (U)_repository;
        //}

        //public virtual bool Add(T model)
        //{
        //    return _repository.Add(model);
        //}

        //public virtual bool Delete(T model)
        //{
        //    return _repository.Delete(model);
        //}

        //public bool Delete(long id)
        //{
        //    return _repository.Delete(id);
        //}

        //public virtual bool Delete(Expression<Func<T, bool>> condition)
        //{
        //    return _repository.Delete(condition);
        //}

        //public virtual T Get(long id)
        //{
        //    return _repository.Get(id);
        //}

        //public virtual T Get(Expression<Func<T, bool>> condition)
        //{
        //    return _repository.Get(condition);
        //}

        //public virtual IEnumerable<T> GetList(Expression<Func<T, bool>> condition, IQueryOrder<T> orderBy = null)
        //{
        //    return _repository.GetList(condition, orderBy);
        //}

        //public virtual PagedList<T> GetList(Expression<Func<T, bool>> condition, long pageIndex, long pageSize, IQueryOrder<T> orderBy = null)
        //{
        //    return _repository.GetList(condition, pageIndex, pageSize, orderBy);
        //}

        //public virtual bool Update(T model)
        //{
        //    return _repository.Update(model);
        //}

        private IPagedReadRepository<T> _readOnlyRepository;
        private IWriteOnlyRepository<T> _writeOnlyRepository;


        /// <summary>
        /// 获取当仓储
        /// </summary>
        /// <typeparam name="U"></typeparam>
        /// <returns></returns>
        protected U Repository<U>()
        {
            var type = typeof(U);
            if (type == typeof(IPagedReadRepository<T>) || type.GetInterfaces().Contains(typeof(IPagedReadRepository<T>)))
                return (U)_readOnlyRepository;
            return (U)_writeOnlyRepository;
        }

        protected IApiResultFactory ApiResultFactory;

        public ServiceBase(IPagedReadRepository<T> readOnlyRepository, IWriteOnlyRepository<T> writeOnlyRepository)
        {
            _readOnlyRepository = readOnlyRepository;
            _writeOnlyRepository = writeOnlyRepository;
            ApiResultFactory = RuntimeContext.Current.Container.Resove<IApiResultFactory>();
        }

        public virtual bool Add(T model)
        {
            return _writeOnlyRepository.Add(model);
        }

        public virtual bool Delete(T model)
        {
            return _writeOnlyRepository.Delete(model);
        }

        public bool Delete(long id)
        {
            return _writeOnlyRepository.Delete(id);
        }

        public virtual bool Delete(Expression<Func<T, bool>> condition)
        {
            return _writeOnlyRepository.Delete(condition);
        }

        public virtual T Get(long id)
        {
            return _readOnlyRepository.Get(id);
        }

        public virtual T Get(Expression<Func<T, bool>> condition)
        {
            return _readOnlyRepository.Get(condition);
        }

        public virtual IEnumerable<T> GetList(Expression<Func<T, bool>> condition, IQueryOrder<T> orderBy = null)
        {
            return _readOnlyRepository.GetList(condition, orderBy);
        }

        public virtual PagedList<T> GetList(Expression<Func<T, bool>> condition, long pageIndex, long pageSize, IQueryOrder<T> orderBy = null)
        {
            return _readOnlyRepository.GetList(condition, pageIndex, pageSize, orderBy);
        }

        public virtual bool Exists(Expression<Func<T, bool>> condition)
        {
            return _readOnlyRepository.Exists(condition);
        }

        public virtual bool Update(T model)
        {
            return _writeOnlyRepository.Update(model);
        }

        /// <summary>
        /// 捕获性执行
        /// </summary>
        /// <param name="action">执行的业务</param>
        /// <param name="exceptionAction">异常动作</param>
        /// <param name="finishAction">结束操作</param>
        /// <returns></returns>
        public IApiResult<R> Execute<R>(Func<IApiResult<R>> action, Action<Exception> exceptionAction = null, Action finishAction = null)
        {
            try
            {
                return action?.Invoke();
            }
            catch (Exception ex)
            {
                exceptionAction?.Invoke(ex);
                return ApiResultFactory.Error<R>(ResultCode.InnerException, ex);
            }
            finally
            {
                finishAction?.Invoke();
            }
        }

        public IApiResult<List<long>> AddBatch(IEnumerable<T> senderSessions)
        {
            return Execute(() =>
            {
                Repository<IWriteOnlyRepository<T>>().BeginTransaction();
                var ids = new List<long>();
                foreach (var sender in senderSessions)
                {
                    if (Add(sender))
                    {
                        ids.Add(sender.Id);
                    }
                    else
                    {
                        throw new Exception("添加失败");
                    }
                }
                Repository<IWriteOnlyRepository<T>>().CommitTransaction();

                return ApiResultFactory.Success(ResultCode.Success, "Ok", ids);
            }, ex =>
            {
                Repository<IWriteOnlyRepository<T>>().RollbackTransaction();
            });
        }
        public void BeginTransaction()
        {
            _writeOnlyRepository.BeginTransaction();
        }

        public void CommitTransaction()
        {
            _writeOnlyRepository.CommitTransaction();
        }

        public void RollbackTransaction()
        {
            _writeOnlyRepository.RollbackTransaction();
        }
    }
}
